package com.mall.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.mall.constant.MessageConstant;
import com.mall.constant.StatusConstant;
import com.mall.dto.CategoryPageQueryDTO;
import com.mall.exception.BaseException;
import com.mall.po.Category;
import com.mall.mapper.CategoryMapper;
import com.mall.po.Goods;
import com.mall.result.PageResult;
import com.mall.service.CategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 分类表 服务实现类
 * </p>
 *
 * @author itlxc
 * @since 2024-04-18
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    /**
     * 分类分页查询
     * @param categoryPageQueryDTO
     * @return
     */
    @Override
    public PageResult categoryPageQuery(CategoryPageQueryDTO categoryPageQueryDTO) {
        // 查询条件
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<Category>()
                .like(StringUtils.isNotBlank(categoryPageQueryDTO.getName()),
                        Category::getName, categoryPageQueryDTO.getName())
                .eq(categoryPageQueryDTO.getType() != null,
                        Category::getType, categoryPageQueryDTO.getType())
                .orderByAsc(Category::getSort)
                .orderByDesc(Category::getUpdateTime);
        Page<Category> page = page(new Page<>(categoryPageQueryDTO.getPage(), categoryPageQueryDTO.getPageSize()), queryWrapper);
        return new PageResult(page.getTotal(), page.getRecords());
    }

    /**
     * 根据id删除分类
     * @param id
     */
    @Override
    public void delCategoryById(Long id) {
        // 启用中的分类无法删除
        Category category = getById(id);
        if (Objects.equals(category.getStatus(), StatusConstant.ENABLE)) {
            throw new BaseException(MessageConstant.CATEGORY_NOT_DEL);
        }
        // 分类关联了商品不能删除
        List<Goods> goodsList = Db.lambdaQuery(Goods.class)
                                    .eq(Goods::getCategoryId, id)
                                    .list();
        if (CollUtil.isNotEmpty(goodsList)) {
            throw new BaseException(MessageConstant.CATEGORY_BE_RELATED_BY_GOOD);
        }
        removeById(id);
    }
}
